/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Post;

import Model.PostInterface;
import DAO.Usuario.HibernateUtil;
import Model.Post;
import Model.Localizacao;
import com.google.gson.Gson;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import org.apache.commons.codec.binary.Base64;
import org.hibernate.Session;

/**
 *
 * @author Radek
 */
@Path("/post")
public class PostService {
    
    public  Gson gson = new Gson();

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    public void sayHello(String json) {

        Post pt = new Post();
        Localizacao loc = new Localizacao();
        PostInterface post = new PostInterface();
         FileOutputStream imageOutFile = null;
        
        
        post = gson.fromJson(json, PostInterface.class);
        long time = System.currentTimeMillis();
        String outputImageaPath = "../webapps/PortalCidadao/images/" + time + ".jpg";
      //   String outputImageaPath = "c:/tmp/" + time + ".jpg";

        byte[] imageByteArray = decodeImage(post.getImagem());

        // Write a image byte array into file system
       
        try {
            imageOutFile = new FileOutputStream(outputImageaPath);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(PostService.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            imageOutFile.write(imageByteArray);
        } catch (IOException ex) {
            Logger.getLogger(PostService.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            imageOutFile.close();
        } catch (IOException ex) {
            Logger.getLogger(PostService.class.getName()).log(Level.SEVERE, null, ex);
        }

        loc.setLatitude(post.getLatitude());
        loc.setLongitude(post.getLongitude());
        loc.setLocal(post.getLocal());
        pt.setCodCategoria(post.getCodCategoria());
        pt.setCodUsuario(post.getUsuario());
        pt.setDescricao(post.getDescricao());
        pt.setImagem("/images//" + time + ".jpg");
        pt.setLocalizacao(loc);
        pt.setTitulo(post.getTitulo());


      

        Session session = HibernateUtil.getSession();
        HibernateUtil.beginTransaction();
        session.save(loc);
        session.save(pt);
        HibernateUtil.commitTransaction();
        HibernateUtil.closeSession();

    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getCoordenates() {
        String json = null;
        ArrayList<Localizacao> lista = null;
         SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy ");
        Session session =null;
        try {
            session=HibernateUtil.getSession();
            ArrayList<PostInterface> postInterface = new ArrayList<PostInterface>();
            HibernateUtil.beginTransaction();
            lista = (ArrayList<Localizacao>) session.createQuery("from Localizacao").list();
            HibernateUtil.commitTransaction();

            ArrayList<Post> arr;

            for (int i = 0; i < lista.size(); i++) {
                PostInterface ps = new PostInterface();
                
                arr = new ArrayList<Post>(lista.get(i).getPosts());
                if(!arr.isEmpty()){
                ps.setCodCategoria(arr.get(0).getCodCategoria());
                ps.setDescricao(arr.get(0).getDescricao());
                ps.setImagem(arr.get(0).getImagem());
                ps.setLatitude(lista.get(i).getLatitude());
                ps.setLocal(lista.get(i).getLocal());
                ps.setLongitude(lista.get(i).getLongitude());
                ps.setUsuario(arr.get(0).getCodUsuario());
                ps.setTitulo(arr.get(0).getTitulo());
                ps.setCod(arr.get(0).getCod());
                ps.setData(sdf.format(arr.get(0).getData()));
                postInterface.add(ps);
                }
                
            }
                json = gson.toJson(postInterface);

        } catch (Exception e) {
            System.out.println(e);
            session.getTransaction().rollback();

        } finally {
            HibernateUtil.closeSession();
        }

        return json;
    }

    public static byte[] decodeImage(String imageDataString) {
        return Base64.decodeBase64(imageDataString);
    }
}
